package com.study.spmongodb.wwj.juc.utils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/13 17:54
 */
public class ConditionExample {
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();

    private static int data = 0;
    private static volatile boolean noUse = true;

    private static void buildData() {
        lock.lock();
        try {
            while (noUse) {
                condition.await();
            }
            data++;
            System.out.println("p:" + data);
            TimeUnit.SECONDS.sleep(1);
            noUse = true;
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private static void useData() {

        lock.lock();
        try {
            while (!noUse) {
                condition.await();
            }
            TimeUnit.SECONDS.sleep(1);
            System.out.println("c:" + data);
            noUse = false;
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        new Thread(() -> {
            while (true) {
                buildData();
            }
        }).start();

        new Thread(() -> {
            while (true) {
                useData();
            }
        }).start();

        new Thread(() -> {
            while (true) {
                useData();
            }
        }).start();

    }
}
